<template>
  <div class="address-container">
    <call-back />
    <div class="address-header">
      <h2 class="address-title">您的地址 ({{ addresses.length }}/20)</h2>
    </div>

    <div class="address-list">
      <!-- 添加地址卡片 -->
      <div class="address-card add-card" @click="showAddressDialog()">
        <div class="add-icon">
          <el-icon :size="40">
            <Plus />
          </el-icon>
        </div>
        <div class="add-text">添加地址</div>
      </div>

      <!-- 地址卡片列表 -->
      <div v-for="(address, index) in addresses" :key="index" class="address-card"
        :class="{ 'selected-card': address.isSelected }">
        <div class="address-content">
          <div class="address-name">{{ address.contactName }}</div>
          <div class="address-detail">{{ address.customerAddress }}</div>
          <div class="address-detail">{{ address.cityName }},{{ address.cityCode }}</div>
          <div class="address-detail">{{ address.countryCodePrefix }}</div>
          <div class="address-phone">手机号: {{ address.countryCodePrefix }} {{ address.phoneNumber }}</div>
          <div class="address-actions">
            <span class="action-link" @click="editAddress(address)">编辑</span> |
            <span class="action-link" @click="deleteAddress(address)">删除</span> |
            <span class="action-link" :class="{ 'disabled': address.isDefault === 1 }"
              @click="address.isDefault !== 1 ? setDefaultAddress(address) : null">
              {{ address.isDefault === 1 ? '我的默认地址' : '设为默认地址' }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增国家选择对话框 -->
    <el-dialog v-model="countryDialogVisible" title="选择国家/地区" width="350px">
      <!-- v-model绑定selectedCountry（已正确绑定） -->
      <el-select v-model="selectedCountry" placeholder="请选择国家/地区" @change="handleCountrySelect" style="width: 100%">
        <el-option v-for="country in countryList" :key="country.code" :label="`${country.name} (${country.code})`"
          :value="country">
          <div class="prefix-option">
            <span>{{ country.name }}</span>
            <span>{{ country.code }}</span>
          </div>
        </el-option>
      </el-select>
    </el-dialog>

    <!-- 地址表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEditing ? '编辑地址' : '添加地址'" width="500px" :close-on-click-modal="false">
      <el-form :model="addressForm" label-width="80px" :rules="rules" ref="addressFormRef">
        <div class="current-shipping">
          <span>当前配送至</span>
          <span class="country-name">{{ currentCountryName }}</span>
          <el-button type="text" class="switch-btn" @click="showCountryDialog">切换 ></el-button>
        </div>

        <el-form-item label="姓名" prop="contactName">
          <el-input v-model="addressForm.contactName" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="手机号" prop="phoneNumber">
          <div class="phone-input-group">
            <el-input v-model="addressForm.countryCodePrefix" class="phone-prefix" disabled />
            <el-input v-model="addressForm.phoneNumber" class="phone-number" placeholder="请输入手机号" />
          </div>
        </el-form-item>

        <div class="address-section">
          <div class="section-title">地址</div>
          <div class="city-state-zip">
            <el-form-item label="省市县" prop="state" class="state-item">
              <el-select v-model="addressForm.cityCode" placeholder="选择省市县">
                <el-option v-for="item in administrativeDivisions" :key="item.cityCode" :label="item.cityName"
                  :value="item.cityCode" />
              </el-select>
            </el-form-item>

            <el-form-item label="邮政编码" prop="cityCode" class="zip-item">
              <el-input v-model="addressForm.cityCode" disabled />
            </el-form-item>
          </div>

          <el-form-item label="详细地址" prop="customerAddress">
            <el-input v-model="addressForm.customerAddress" placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元号等信息" />
          </el-form-item>
        </div>

        <el-form-item>
          <el-checkbox v-model="isDefaultChecked">设为默认地址</el-checkbox>
        </el-form-item>

        <div class="dialog-footer">
          <el-button round @click="dialogVisible = false">取消</el-button>
          <el-button type="success" round @click="submitForm">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { customerAddressApi } from '@/api/customer/address/index'
import type { CustomerAddressListVO } from '@/api/customer/address/index'
import { administrativeDivisionApi } from '@/api/administrativedivision/index'
import type { AdministrativeDivisionVO } from '@/api/administrativedivision/index'
import CallBack from '@/components/callback/index.vue'


const countryList = ref([
  { name: '中国', code: '+86' },
])

// 地址列表
const addresses = ref<CustomerAddressListVO[]>([])

watch(() => addresses.value.length, (New, Old) => {
  if (New == 1 && addresses.value[0].isDefault !== 1) {
    let id = addresses.value[0].id
    try {
      // 调用接口设置默认地址
      customerAddressApi.setDefault(id)
      getList()
      ElMessage.success('已设为默认地址')
    } catch (error) {
      ElMessage.error('设置默认地址失败')
    }
  }
})
const autoDefaultAddress = () => {
  console.log(addresses.value.length, "length");

}

const administrativeDivisions = ref<AdministrativeDivisionVO[]>([])

const isDefaultChecked = computed({
  get() {
    return addressForm.isDefault === 1  // 当isDefault为1时返回true（选中状态）
  },
  set(val) {
    addressForm.isDefault = val ? 1 : 0  // 选中时设为1，未选中设为0
  }
})

const currentCountryName = computed(() => {
  const country = countryList.value.find(item => item.code === addressForm.countryCodePrefix)
  return country?.name || ''
})

// 表单相关
const dialogVisible = ref(false)
const isEditing = ref(false)
const addressFormRef = ref<FormInstance>()

// 表单数据
const addressForm = reactive<CustomerAddressListVO>({
  id: 0,// 主键id
  customerAddress: '', // 客户地址
  cityCode: '', // 城市编号
  contactName: '', // 联系人姓名
  phoneNumber: null, // 联系人电话（Java的Long对应TS的number）
  countryCodePrefix: '+86', // 国家代码前缀
  cityName: '',
  isDefault: 0, // 是否默认地址（可能为0/1等数值表示）
})
const getList = async () => {
  const res = await customerAddressApi.getList()
  addresses.value = res
}

// 表单验证规则
const rules = {
  contactName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phoneNumber: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  cityCode: [{ required: true, message: '请选择省市县', trigger: 'change' }],  // 对应省市县选择框
  customerAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]  // 修正为customerAddress
}

// 初始化数据
onMounted(() => {
  getList();
})

// 显示地址对话框
const showAddressDialog = async (address?: CustomerAddressListVO) => {
  console.log(addressForm.countryCodePrefix)
  const res = await administrativeDivisionApi.getList(addressForm.countryCodePrefix)
  administrativeDivisions.value = res  // 假设返回类型为AdministrativeDivisionVO[]
  if (address) {
    isEditing.value = true
    Object.assign(addressForm, address)
    selectedCountry.value = countryList.value.find(
      c => c.code === addressForm.countryCodePrefix
    ) || null
  } else {
    isEditing.value = false
    Object.assign(addressForm, {
      id: 0,// 主键id
      customerAddress: '', // 客户地址
      cityCode: '', // 城市编号
      contactName: '', // 联系人姓名
      phoneNumber: null, // 联系人电话（Java的Long对应TS的number）
      countryCodePrefix: '+86', // 国家代码前缀
      cityName: '',
      isDefault: 0, // 是否默认地址（可能为0/1等数值表示）
    })
    selectedCountry.value = countryList.value.find(c => c.code === '+86') || null
  }
  dialogVisible.value = true
}

// 编辑地址
const editAddress = (address: CustomerAddressListVO) => {
  showAddressDialog(address)
}

// 删除地址
const deleteAddress = (address: CustomerAddressListVO) => {
  ElMessageBox.confirm(
    `
      <div>
        <p style="margin-bottom: 10px;">地址删除后将不可恢复，是否确定删除？</p>
        <p style=" font-size: 13px; margin: 40px 0;">
          请注意：删除此地址并不会删除发往该地址的任何待发货订单。为确保未来订单的连续配送，请更新地址设置。
        </p>
      </div>
    `,
    '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    customClass: 'no-icon-message-box',
    // type: 'warning',
    dangerouslyUseHTMLString: true,
    roundButton: true,

    // customClass: 'delete-address-message-box'
  }).then(async () => {
    await customerAddressApi.delete(address.id);
    getList()
    ElMessage.success('删除成功')
  }).catch(() => { })
}

// 设置默认地址
const setDefaultAddress = async (address: CustomerAddressListVO) => {
  try {
    // 调用接口设置默认地址
    await customerAddressApi.setDefault(address.id)
    getList()
    ElMessage.success('已设为默认地址')
  } catch (error) {
    ElMessage.error('设置默认地址失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!addressFormRef.value) return

  await addressFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构造后端需要的参数对象
        const commonParams = {
          customerAddress: addressForm.customerAddress,  // 详细地址映射
          cityCode: addressForm.cityCode,                            // 需补充城市编码（根据业务实际情况）
          contactName: addressForm.contactName,          // 姓名映射
          phoneNumber: Number(addressForm.phoneNumber), // 电话号码转换为数字
          countryCodePrefix: addressForm.countryCodePrefix,  // 国家代码前缀
          isDefault: addressForm.isDefault
        }

        if (isEditing.value) {
          // 更新地址（调用update接口）
          await customerAddressApi.update({
            ...commonParams,
            id: addressForm.id
          })
          ElMessage.success('地址更新成功')
        } else {
          // 新增地址（调用create接口）
          await customerAddressApi.create(commonParams)
          // 本地添加（可选：也可以重新调用getList刷新）
          ElMessage.success('地址添加成功')
        }
        getList()
        dialogVisible.value = false
      } catch (error) {
        ElMessage.error(isEditing.value ? '更新地址失败' : '添加地址失败')
      }
    }
  })
}

// 新增国家选择相关状态
const countryDialogVisible = ref(false)
const selectedCountry = ref<{ name: string; code: string } | null>(null)

// 显示国家选择对话框
const showCountryDialog = () => {
  countryDialogVisible.value = true
}

// 处理国家选择
const handleCountrySelect = (country: { name: string; code: string }) => {
  if (country) {
    addressForm.countryCodePrefix = country.code
    countryDialogVisible.value = false
  }
}
</script>

<style scoped>
.action-link.disabled {
  color: #000;
  /* 黑色文字 */
  cursor: not-allowed;
  /* 不可操作光标 */
  pointer-events: none;
  /* 彻底阻止点击事件 */
}

.address-container {
  position: relative;
  background-color: #fff;
  padding: 20px;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.address-title {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 10px;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.address-card {
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
  padding: 20px;
  height: 200px;
  position: relative;
  transition: all 0.3s;
}

.address-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.selected-card {
  border: 2px solid #ff4d4f;
}

.add-card {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border: 1px dashed #dcdfe6;
}

.add-icon {
  color: #909399;
  margin-bottom: 10px;
}

.add-text {
  color: #909399;
  font-size: 16px;
}

.address-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.address-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.address-detail {
  color: #606266;
  margin-bottom: 5px;
  font-size: 14px;
}

.address-phone {
  color: #606266;
  margin-bottom: 10px;
  font-size: 14px;
}

.address-actions {
  margin-top: auto;
  display: flex;
  gap: 5px;
  color: #606266;
  font-size: 14px;
}

.action-link {
  color: #409eff;
  cursor: pointer;
}

.action-link:hover {
  color: #66b1ff;
}

/* 表单样式 */
.current-shipping {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.country-name {
  font-weight: bold;
  margin: 0 10px;
}

.switch-btn {
  color: #409eff;
}

.phone-input-group {
  display: flex;
  gap: 10px;
}

.phone-prefix {
  width: 180px;
}

.phone-number {
  flex: 1;
}

.prefix-option {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.address-section {
  margin-top: 20px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 15px;
}

.city-state-zip {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

@media (max-width: 1200px) {
  .address-list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .address-list {
    grid-template-columns: 1fr;
  }

  .city-state-zip {
    grid-template-columns: 1fr;
  }
}

</style>
<style>

/* 绿色确认按钮 */
.no-icon-message-box .el-button--primary {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.no-icon-message-box .el-button--primary:hover {
  background: linear-gradient(135deg, #5daf34 0%, #529b2e 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(103, 194, 58, 0.4);
}
</style>
